// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()
//所有发表的文章的集合
const tree_hole_story = db.collection("tree_hole_story")
//所有用户对文章点赞的集合
const user_zan_story = db.collection("user_zan_story")


// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  //获取用户点赞的文章
  let userZanStory = null
  const result1 = await user_zan_story
    .where({ _openid: wxContext.OPENID })
    .get()
  if (result1.data.length !== 0) {
    userZanStory = result1.data[0].zanStory
  }
  //返回的文章数据
  let stories = null
  //获取到所有的已发表故事
  const result2 = await tree_hole_story
    .where({})
    .orderBy("create_time", "desc")
    .get()
  /**
   * 并且判断用户是否对该故事点赞
   */
  //如果用户从未点赞过故事
  if (userZanStory === null || userZanStory.length === 0) {
    stories = result2.data.map(item => {
      item.isLike = false
      return item
    })
  } else {
    //如果用户给文章点过赞
    userZanStory.forEach(storyId => {
      stories = result2.data.map(item => {
        if (storyId === item._id) {
          item.isLike = true
        } else if(storyId !== item._id && !item.isLike) {
          item.isLike = false
        }
        return item
      })
    })
  }
  return stories
}